<?php
namespace control;
class productSetupStoreClass extends adIndexClass
{
	private const page        = 'productSetupStore'; # 权限
	private const table       = 'material';
	private const tableTarget = 'store_product';
	private const title       = '商品信息';
	private array $stateOption = ['未上架', '已上架', '已下架'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "物料名称",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'barcode'         => [
                        'name'  => '条码',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'unit'          => [
                        'name'  => '主单位',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '零售价',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'invNum'          => [
                        'name'  => '库存数量',
                        'width' => 100,
                    ],
                    'available'          => [
                        'name'  => '可订数量',
                        'width' => 100,
                    ],
                    'state'          => [
                        'name'  => '商品状态',
                        'width' => 100,
                    ],
                    'grounding'          => [
                        'name'  => '是否上架',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

	public static function getDepartmentAll($data = []): string
	{
		// 条件
		$data['where'] = $data['where'] ?? "pid='0'";
		// 点击事件
		$data['click'] = $data['click'] ?? "replaceDetail(this,'" . self::page . "')";
		// 结果
		$result = find(['table' => 'material_type', 'where' => $data['where'] . " and coid = '" . self::$coid . "' order by list asc"]);
		$style  = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
		$temp   = "<ul $style {$data['where']}>";
		if ($result['array']) {
			foreach ($result['array'] as $value) {
				// 角标
				$arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
				// 判断下级是否存在
				$data['where'] = " pid='{$value['id']}' ";
				$has           = query('material_type', $data['where']);
				$dots          = "";
				if ($has['id']) {
					$temp .= "<li class='arrow-li' data-id='{$value['id']}' onclick=\"{$data['click']}\">{$arrow}{$dots}<span class='textcontent'>$value[name]</span></li>";
					$temp .= self::getDepartmentAll($data);
				} else {
					$temp .= "<li class='arrow-no-li'  data-id='{$value['id']}' onclick=\"{$data['click']}\">{$dots}<span class='textcontent'>$value[name]</span></li>";
				}
			}
		}
		$temp .= '</ul>';

		return $temp;
	}

	/**
	 * 异步加载
	 */
	public function homeRightJson(): bool|string
	{
		$json['html'] = $this->homeRight();
		return json_encode($json, 320);
	}

	public function homeRightJsonSearch(): bool|string
	{
		return $this->homeSearch();
	}

	/**
	 * 左侧搜索框
	 *
	 * @return string
	 */
	public function getContainerLeftJson(): string
	{
		$option['click'] = 'replaceContent(this, \'' . self::page . '\')';
		$json['html']    = self::getDepartmentAll($option);
		return json_encode($json, 320);
	}


	public function homeHtml(): string
	{
		//返回
		$rightHtml       = $this->homeRight();
		$option['click'] = 'replaceContent(this, \'' . self::page . '\')';
		$all             = self::getDepartmentAll($option);
        return componentClass::leftNav([
            'title'=>'搜索分类',
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
	}

	/*列表页-查询条件*/
	public function home(): string
	{
		//返回
		return $this->homeFun($this->homeHtml());
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $typeId = $this->post('objId') ?? null;
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "是否上架" => checkbox([
                        "name"    => "state",
                        "value"   => $this->stateOption,
                        "checked" => [],
                    ]).hidden(array('name' => 'typeId', 'value' => $typeId)),
                ],
                [
                    "物料编码"   => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "materialName")),
                    "规格型号"   => text(array("name" => "model")),
                ],
                [
                    "商品状态" => select(["name" => "mstate", 'option' => ['启用', '停用']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }


	public function homeRight(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}', 'stateSwitch', {type:'上架'})\" class='spanButton'>批量上架</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}', 'stateSwitch', {type:'下架'})\" class='spanButton'>批量下架</span>\n";
        }
		//返回
		return $this->search($html, layout: 'pop', toolButton: $button);
	}

	public function homeSearch(): bool|string
	{
		$where = " m.coid = '".self::$coid."' ";
		$like  = [
			"m.name"  => $this->post('materialName'),//名称
			"m.code"  => $this->post('code'),//编码
			"m.model" => $this->post('model'),//规格型号
            "m.typePath" => $this->post('typeId'),
		];
		//全等查询数组
		$equal = [
			"m.state"  => $this->post('mstate'),
		];
		// 状态
		if ($this->post('state')) {
			if (count($this->post('state')) == 3) {
				$where .= '';
			} else {
				$mlWhere = $stWhere = '';
				if (in_array('未上架', $this->post('state'))) {
					$mlWhere = " m.id NOT IN (SELECT materialId FROM `" . self::tableTarget . "` WHERE `coid` = '" . self::$coid . "' ) ";
				}
				$stateArr = array_diff($this->post('state'), ['未上架']);
				if ($stateArr) {
					$stWhere = " m.id IN (SELECT materialId FROM `" . self::tableTarget . "` WHERE `state` IN ('" . implode("','", $stateArr) . "')) ";
				}
				if ($mlWhere && $stWhere) {
					$where .= " AND ($mlWhere OR $stWhere) ";
				} else {
					$where .= $mlWhere ? ' AND ' . $mlWhere : ($stWhere ? ' AND ' . $stWhere : '');
				}
			}
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where                       .= search(["like" => $like, "=" => $equal]);
		$page                        = $this->page([
			'field' => 'm.id,m.code,m.name,m.model,m.unit,m.state,m.time,m.barcode',
			"table" => self::table . ' as m',
			"where" => $where . ' group by m.id ',
			"order" => $orderBy['orderBy'],
		]);
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = [
				"box"    => [
					"name" => "listId", "value" => $array['id'],
				],
				"detail" => [
					"title" => self::title . "详情",
					"click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
				],
			];
            $liButton[] = $this->dominate($dominate);
            $info      = query(self::tableTarget, " materialId = '$array[id]'  ");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "price":
                        $row[] = $info['price'] ?: '-';
                        break;
                    case "invNum":
                        $invNum   = inventoryBalanceClass::inventoryNum($array['id']);
                        $row[] = $invNum;
                        break;
                    case "available":
                        // 可定数量
                        $available = 0;
                        $row[] = $available;
                        break;
                    case "grounding":
                        $row[] = $info['state'] ?: '未上架';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;

		return json_encode($json, 320);
	}


	/**
	 * 明细
	 *
	 * @return bool|string
	 */
	public function detail(): bool|string
	{
        $info   = query(self::table, " id = '" . $this->get('id') . "' ");
		if (!$this->power(self::page, "see")) {
			$html = "你没有查看商品信息的权限";
		} elseif (empty($info['id'])) {
			$html = "未找到此商品信息";
		} else {
			$target = query(self::tableTarget, " materialId = '$info[id]' ");
			$data   = [
				"id"    => $info['id'],
				"title" => $info['name'],
				'menu'  => [
					"detail" => "基本信息",
					'client' => '可售范围',
				],
			];
			//按钮
			$button = [];
			if ($this->power(self::page, "edit")) {
				$state    = $info['state'] != '已上架' ? '上架' : '下架';
				$button[] = [
					"name"  => $state,
					"type"  => "点击事件",
					'title' => '修改状态',
					"fun"   => "layer('" . $this->get('cla') . "','stateSwitch',{id:'" . $info['id'] . "',type:'$state'})",
					'style' => 'li-btn-blue-bg',
				];
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				[
					[
						"分类"     => $info['typeName'],
						"物料编码" => $info['code'],
						"物料名称" => $info['name'],
                        "规格型号" => $info['model'],
					],
					[
						"主单位"   => $info['unit'],
						"辅单位1" => $info['unit_one'],
						"辅单位2" => $info['unit_two'],
						"状态"    => $info['state'],
					],
					[
						"备注" => pre($info['text']),
					],

				],
				'参数'     => [
					[
						'辅单位1换算' => $info['unit_one_num'],
						'辅单位2换算' => $info['unit_two_num'],
                        '商品条码'             => $info['barcode'],
					],
					[
						'零售价（' . static::$unit . '）' => text(['name' => 'price', 'value' => $target['price'] ?: '', 'class' => 'text textPrice', 'keyup' => 'updateInfo', 'data' => ['field' => 'price', 'id' => $info['id']]]),
						'新品'                 => radio(['name' => 'isNew', 'value' => ['是', '否'], 'checked' => $target['isNew'] ?: '否', 'change' => 'updateInfo', 'data' => ['field' => 'isNew', 'id' => $info['id']],]),
					],
				],
				'商品图片' => [
					[
						fileUploadClass::showImg($info['id'], '物料档案'),
					],
				],
				'系统信息' => [
					[
						"创建人"   => self::findStaff($info['stid']),
						"更新时间" => $info['updateTime'],
						"创建时间" => $info['time'],
					],
				],
			]);
			//生成页面
			$html = $this->tab($data);
		}
		$html .= <<<EOT
<script>
function updateInfo(that) {
  const id = $(that).data('id'),
  		val = $(that).val(),
  		field = $(that).data('field')
  if(id.length || val.length || field.length){
	  $.post(root+'control/adIndex.html?cla=productSetupStore&fun=updateInfo', {id: id, field: field, val: val}, function(res) {
	  	if(res.warn === 2){
              window.location.reload()
	  	}else{
              msg(res.warn)
	  	}
	  },'json')
  }
}
</script>
EOT;

		//返回
		return $html;
	}

	/**
	 * 更新信息
	 *
	 * @return string
	 */
	function updateInfo(): string
	{
		$id    = $this->post('id');
		$field = $this->post('field');
		$val   = $this->post('val');
		if (empty($id) || empty($field) || empty($val)) {
			$json['warn'] = '参数错误';
		} else {
			$json['warn'] = static::update([
				'table' => self::tableTarget,
				'field' => [
					$field => $val,
				],
				'where' => " materialId = '$id' ",
			]);
			if (in_array($json['warn'], ['新增成功', '更新成功'])) {
				$json['warn'] = 2;
			}
		}
		return json_encode($json, 320);
	}


	/**
	 * 可售范围
	 *
	 * @return string
	 */
	public function client(): string
	{
		$where = " coid = '" . self::$coid . "' and materialId = '{$this->get('id')}' ";
		$page  = $this->page([
			"table" => 'store_client_price',
			"where" => $where,
			"order" => " `time` desc ",
		]);
		//获取表头
		$tr[] = ['客户编码', '客户名称', '协议价（'.static::$unit.'）', '协议折扣（%）'];
		//获取记录
		foreach ($page['array'] as $array) {
			$kehu = query('kehu', " khid = '$array[khid]' ");
			$tr[] = [$kehu['orderNo'], $kehu['companyName'], $array['agreedPrice'], $array['agreedDiscount'] > 0 ? ($array['agreedDiscount'] * 100) . '%' : ''];
		}
		//控件
		$json['html'] = "<div class='p-10'>" . $page['hint'] . "<form name='topicForm'>" . $this->tableMany(array("tr" => $tr, "displayFields" => false)) . "</form>" . $page['button']."</div>";
		return json_encode($json, 320);
	}


	/**
	 * 启用/停用
	 */
	public function stateSwitch(): bool|string
	{
		$type = $this->post('type');
		//生成表单
		$html = $this->layerEdit(array(
			"table"     => array(
				array(
					"提示：" => "是否修改所选数据状态为：" . $type,
				),
			), 'hidden' => hidden(array('name' => 'type', 'value' => $type)),
		));
		//返回
		return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitchEdit(): string
	{
		$idArr = $this->post('id') ? [$this->post('id')] : (array)$this->post('listId');
		$state = $this->post('type');
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有" . self::title . "的编辑权限";
		} elseif (empty($idArr) || !is_array($idArr)) {
			$json['warn'] = "请选择数据";
		} elseif (!in_array($state, ['上架', '下架'])) {
			$json['warn'] = "类型错误";
		} else {
			$param = [
				'state' => $state,
			];
			$text  = '';
			$x     = 0;
			foreach ($idArr as $id) {
				$where = generateWhere([
					'coid'          => self::$coid,
					'materialId' => $id,
				]);
                $material = query(self::table, " id = '{$id}' ", " id,typeId ");
                if (static::isNull($material['id'])) {
                    continue;
                }
				$info = query(self::tableTarget, $where);
				if ($info['state'] == $state) {
					continue;
				}
				if (static::isNull($info['id'])) {
					$field    = array_merge([
						'id'            => self::getNo(),
						'coid'          => self::$coid,
						'stid'          => self::$stid,
						'materialId'    => $material['id'],
						'typeId'        => $material['typeId'],
					], $param);
					$bool     = static::insert([
						'table' => self::tableTarget,
						'field' => $field,
					]);
				} else {
					$field = array_merge([], $param);
					$bool  = static::update([
						'table' => self::tableTarget,
						'field' => $field,
						'where' => $where,
					]);
				}
				if (in_array($bool, ["新增成功", "更新成功"])) {
					$x++;
					//添加日志
					$type = mb_substr($bool, 0, 2, 'utf-8');
					$text .= $this->control['name'] . $type . "了" . self::title . "的状态为【{$state}】， id：【" . $id . '】<br>';
				}
			}
			if ($x < 1) {
				$json['warn'] = '操作失败，未选择记录或记录状态相同';
			} else {
				$_SESSION['warn'] = '操作成功，修改了' . $x . '条记录';
				$json['warn']     = 2;

				if ($text) {
					$this->logText(["type" => self::page, "text" => $text]);
				}
			}
		}
		//返回
		return json_encode($json, 320);
	}
}
